<?php
/**
 * 后台意见反馈管理API
 * 支持意见反馈的查看、回复、状态管理等功能
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 简单的token验证
function verifyAdminToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        $sql = "SELECT au.*, ar.permissions 
                FROM admin_users au 
                LEFT JOIN admin_roles ar ON au.role_id = ar.id 
                WHERE au.id = ? AND au.status = 'active'";
        $stmt = $pdo->prepare($sql);
        // 简化token验证，实际应该有更复杂的验证逻辑
        $stmt->execute([1]); // 临时使用admin用户
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return false;
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 验证管理员权限
$token = getAuthToken();
$admin = verifyAdminToken($token);

if (!$admin) {
    error('未授权的访问', 401);
}

// 获取意见反馈列表
function getFeedbackList() {
    global $pdo;
    
    try {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = min(50, max(10, (int)($_GET['limit'] ?? 20)));
        $offset = ($page - 1) * $limit;
        
        // 构建查询条件
        $where = "1=1";
        $params = [];
        
        // 状态筛选
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where .= " AND f.status = ?";
            $params[] = $_GET['status'];
        }
        
        // 反馈类型筛选
        if (isset($_GET['feedback_type']) && !empty($_GET['feedback_type'])) {
            $where .= " AND f.feedback_type = ?";
            $params[] = $_GET['feedback_type'];
        }
        
        // 关键词搜索
        if (isset($_GET['search']) && !empty($_GET['search'])) {
            $where .= " AND (f.title LIKE ? OR f.content LIKE ?)";
            $params[] = '%' . $_GET['search'] . '%';
            $params[] = '%' . $_GET['search'] . '%';
        }
        
        // 查询总数
        $countSql = "SELECT COUNT(*) FROM feedback f WHERE $where";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetchColumn();
        
        // 查询列表数据
        $sql = "SELECT 
                    f.id,
                    f.user_id,
                    f.feedback_type,
                    f.title,
                    f.content,
                    f.images,
                    f.contact_phone,
                    f.status,
                    f.reply,
                    f.created_at,
                    f.updated_at,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name
                FROM feedback f
                LEFT JOIN users u ON f.user_id = u.id
                WHERE $where
                ORDER BY f.created_at DESC
                LIMIT ? OFFSET ?";
        
        // 将 LIMIT 和 OFFSET 作为整数绑定
        $stmt = $pdo->prepare($sql);
        
        // 绑定前面的查询参数
        for($i = 0; $i < count($params); $i++) {
            $stmt->bindValue($i + 1, $params[$i]);
        }
        
        // 绑定 LIMIT 和 OFFSET 参数为整数
        $stmt->bindValue(count($params) + 1, (int)$limit, PDO::PARAM_INT);
        $stmt->bindValue(count($params) + 2, (int)$offset, PDO::PARAM_INT);
        
        $stmt->execute();
        $feedbacks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 处理图片字段
        foreach ($feedbacks as &$feedback) {
            $feedback['images'] = json_decode($feedback['images'], true) ?: [];
            
            // 格式化状态
            $feedback['status_text'] = $feedback['status'] == 'pending' ? '待处理' : '已处理';
            
            // 用户信息
            $feedback['user_name'] = $feedback['user_real_name'] ?: $feedback['user_nickname'] ?: '未知用户';
        }
        
        success([
            'list' => $feedbacks,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => (int)$total,
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取反馈列表失败: ' . $e->getMessage(), 500);
    }
}

// 获取意见反馈详情
function getFeedbackDetail() {
    global $pdo;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少反馈ID');
    }
    
    try {
        $sql = "SELECT 
                    f.*,
                    u.nickname as user_nickname,
                    u.real_name as user_real_name,
                    u.phone as user_phone,
                    u.avatar as user_avatar
                FROM feedback f
                LEFT JOIN users u ON f.user_id = u.id
                WHERE f.id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $feedback = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$feedback) {
            error('反馈不存在');
        }
        
        // 处理图片字段
        $feedback['images'] = json_decode($feedback['images'], true) ?: [];
        
        // 格式化状态
        $feedback['status_text'] = $feedback['status'] == 'pending' ? '待处理' : '已处理';
        
        // 用户信息
        $feedback['user_name'] = $feedback['user_real_name'] ?: $feedback['user_nickname'] ?: '未知用户';
        
        success($feedback);
        
    } catch (Exception $e) {
        error('获取反馈详情失败: ' . $e->getMessage(), 500);
    }
}

// 回复意见反馈
function replyFeedback() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? 0;
    $reply = trim($input['reply'] ?? '');
    
    if (!$id) {
        error('缺少反馈ID');
    }
    
    if (!$reply) {
        error('请输入回复内容');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 更新反馈状态和回复
        $sql = "UPDATE feedback SET 
                    reply = ?, 
                    status = 'processed',
                    updated_at = NOW() 
                WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$reply, $id]);
        
        if ($stmt->rowCount() === 0) {
            throw new Exception('反馈不存在或更新失败');
        }
        
        // 记录操作日志
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '意见反馈回复',
            'feedback',
            "回复了反馈ID#{$id}",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '回复成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('回复失败: ' . $e->getMessage(), 500);
    }
}

// 更新反馈状态
function updateFeedbackStatus() {
    global $pdo, $admin;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? 0;
    $status = $input['status'] ?? '';
    
    if (!$id) {
        error('缺少反馈ID');
    }
    
    if (!in_array($status, ['pending', 'processed'])) {
        error('无效的状态值');
    }
    
    try {
        $pdo->beginTransaction();
        
        $sql = "UPDATE feedback SET 
                    status = ?,
                    updated_at = NOW() 
                WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$status, $id]);
        
        if ($stmt->rowCount() === 0) {
            throw new Exception('反馈不存在或更新失败');
        }
        
        // 记录操作日志
        $statusText = $status == 'pending' ? '待处理' : '已处理';
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '意见反馈状态变更',
            'feedback',
            "将反馈ID#{$id}状态更改为：{$statusText}",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '状态更新成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('状态更新失败: ' . $e->getMessage(), 500);
    }
}

// 删除意见反馈
function deleteFeedback() {
    global $pdo, $admin;
    
    $id = $_GET['id'] ?? 0;
    if (!$id) {
        error('缺少反馈ID');
    }
    
    try {
        $pdo->beginTransaction();
        
        // 先获取反馈信息用于日志
        $feedbackSql = "SELECT title FROM feedback WHERE id = ?";
        $feedbackStmt = $pdo->prepare($feedbackSql);
        $feedbackStmt->execute([$id]);
        $feedback = $feedbackStmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$feedback) {
            throw new Exception('反馈不存在');
        }
        
        // 删除反馈
        $sql = "DELETE FROM feedback WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        
        // 记录操作日志
        $logSql = "INSERT INTO admin_operation_logs 
                   (admin_id, username, action, module, description, ip_address, user_agent, created_at) 
                   VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        $logStmt = $pdo->prepare($logSql);
        $logStmt->execute([
            $admin['id'],
            $admin['username'],
            '删除意见反馈',
            'feedback',
            "删除了反馈：「{$feedback['title']}」",
            $_SERVER['REMOTE_ADDR'] ?? '',
            $_SERVER['HTTP_USER_AGENT'] ?? ''
        ]);
        
        $pdo->commit();
        success(null, '删除成功');
        
    } catch (Exception $e) {
        $pdo->rollBack();
        error('删除失败: ' . $e->getMessage(), 500);
    }
}

// 获取反馈统计
function getFeedbackStats() {
    global $pdo;
    
    try {
        // 总体统计
        $totalSql = "SELECT 
                        COUNT(*) as total,
                        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
                        COUNT(CASE WHEN status = 'processed' THEN 1 END) as processed_count
                     FROM feedback";
        $totalStmt = $pdo->query($totalSql);
        $totalStats = $totalStmt->fetch(PDO::FETCH_ASSOC);
        
        // 按类型统计
        $typeSql = "SELECT 
                        feedback_type,
                        COUNT(*) as count
                    FROM feedback 
                    GROUP BY feedback_type 
                    ORDER BY count DESC";
        $typeStmt = $pdo->query($typeSql);
        $typeStats = $typeStmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 最近7天统计
        $recentSql = "SELECT 
                        DATE(created_at) as date,
                        COUNT(*) as count
                      FROM feedback 
                      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
                      GROUP BY DATE(created_at)
                      ORDER BY date DESC";
        $recentStmt = $pdo->query($recentSql);
        $recentStats = $recentStmt->fetchAll(PDO::FETCH_ASSOC);
        
        success([
            'total_stats' => $totalStats,
            'type_stats' => $typeStats,
            'recent_stats' => $recentStats
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getFeedbackList();
                    break;
                case 'detail':
                    getFeedbackDetail();
                    break;
                case 'stats':
                    getFeedbackStats();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'reply':
                    replyFeedback();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'PUT':
            switch ($action) {
                case 'status':
                    updateFeedbackStatus();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'DELETE':
            deleteFeedback();
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>